#!/usr/bin/python
import sys,os,re
sys.path.append(os.path.realpath(".."))
from urllib import unquote
from third import tldextract
from helper import anncheck
import dbapi
import net

global browser
global domain

browser=net.create_browser()
db=net.create_mysql()
domain="http://anilinkz.com/"

def get_page(name_tag):
	global browser
	global domain
	res=browser.open(domain+name_tag)
	return res.read()

def decode_posix(src):
	chars="QWERTYUIOPASDFGHJKLZXCVBNM~!@#$*{}[]-+."
	for char in chars:
		src=src.replace(char,"")
	return re.findall('src="(.*?)"',unquote(src))

def get_video_link(page):
	link=re.findall('document\.write\(unescape\(escapeall\(\'(.*?)\'\)',page)
	if len(link)>0:
		link=decode_posix(link[0])
		return link
	else:
		return None

def get_sources(page):
	srcs=re.findall('id="sources"(.*?)/div',page,re.DOTALL)
	if len(srcs)>0:
		return re.findall('href="(.*?)"',srcs[0])[1:]
	else:
		return None

def get_links(link):
	video_links=[]
	page=get_page(link)
	video_links=get_video_link(page)
	srcs=get_sources(page)
	for src in srcs:
		video_links.extend(get_video_link(get_page(src)))
	return video_links

def parse_epis(page):
	epis=list(re.findall('class="epl".*?class="title".*?href="(.*?)">(.*?)</a>.*?img/inf/1/(.*?)\.png',page,re.DOTALL))
	return epis

def parse_pages(page):
	return re.findall('class="page".*?>(.*?)</a>',page,re.DOTALL)

serie="texhnolyze"
[serie,remote_id]=anncheck.get_tag(serie)
bot="AniLinkz Bot"
ptype=0
product_id=dbapi.get_product_id(db,serie,ptype,remote_id)
season_id=dbapi.get_season_id(db,product_id,ptype,remote_id,"0")
link_provider_id=dbapi.get_link_provider(db,"AniLinkz")

page=get_page("/series/"+serie)
pages=parse_pages(page)
epis=parse_epis(page)

for single in pages:
	print "Getting " + serie + " Episode Listing :" + single 
	epis.extend(parse_epis(get_page("series/"+serie+"?page="+single)))
for i in range(len(epis)):
	if epis[i][2] in ["Advance"]:
		print "Episode " + epis[i][1] + " does not contain video, skipping..."
		epis.pop(i)
		continue
	epis[i]=list(epis[i])
	print "Getting videos for " + epis[i][1]
	links=get_links(epis[i][0])
	for link in links:
		movie_provider_id=dbapi.get_movie_provider(db,tldextract.extract(link).domain)
		if dbapi.add_new_link(db,bot,link,product_id,ptype,remote_id,season_id,movie_provider_id,link_provider_id,epis[i][1]):
			print True
	break